<template>
  <div class="user-center">
    <!-- 顶部封面 -->
    <div class="cover-wrap">
      <div class="cover-mask">
        <div class="cover-emoji">🌄</div>
        <div class="cover-title">Personal Center</div>
        <div class="cover-sub">「记录每一刻闪光」</div>
      </div>
    </div>

    <!-- 主体 -->
    <div class="content-wrap">
      <!-- 返回按钮 -->
      <div class="back-button">
        <a-button type="link" @click="$router.push('/')">
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回主页
        </a-button>
      </div>

      <a-row :gutter="[24, 24]">
        <!-- 左侧：用户档案 -->
        <a-col :xs="24" :lg="8">
          <a-card class="profile-card" :bordered="false">
            <div class="avatar-box">
              <a-avatar
                :size="100"
                :src="userInfo.userAvatar || defaultAvatar"
                class="avatar-main"
              />
              <div class="avatar-badge">😊</div>
              <a-button type="text" class="avatar-edit-btn" @click="handleAvatarChange">
                更换头像
              </a-button>
            </div>

            <div class="username">{{ userInfo.userName }}</div>
            <div class="account">@{{ userInfo.userAccount }}</div>

            <a-divider style="margin: 16px 0">档案</a-divider>

            <div class="profile-list">
              <div class="item">
                <span class="label">身份</span>
                <a-tag :color="userInfo.userRole === 'admin' ? '#ff7eb3' : '#7bc8ff'">
                  {{ userInfo.userRole === 'admin' ? '管理员' : '普通用户' }}
                </a-tag>
              </div>
              <div class="item">
                <span class="label">简介</span>
                <span class="value">{{ userInfo.userProfile || '暂无简介' }}</span>
              </div>
              <div class="item">
                <span class="label">加入于</span>
                <span class="value">{{ formatDate(userInfo.createTime) }}</span>
              </div>
              <div class="item">
                <span class="label">最后更新</span>
                <span class="value">{{ formatDate(userInfo.updateTime) }}</span>
              </div>
            </div>

            <div class="action-btns">
              <a-button type="primary" shape="round" size="large" block @click="handleEditInfo">
                编辑资料
              </a-button>
              <a-button
                shape="round"
                size="large"
                block
                style="margin-top: 12px"
                @click="handleChangePassword"
              >
                修改密码
              </a-button>
            </div>
          </a-card>
        </a-col>

        <!-- 右侧：快捷入口 + 数字卡片 -->
        <a-col :xs="24" :lg="16">
          <!-- 快捷入口 -->
          <a-card title="快捷入口" class="quick-card" :bordered="false">
            <a-row :gutter="16">
              <a-col :span="8">
                <div class="quick-item" @click="$router.push('/picture/create')">
                  <div class="icon">➕</div>
                  <div class="text">上传图片</div>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="quick-item" @click="handleReviewStatusClick">
                  <div class="icon">🔍</div>
                  <div class="text">审核状态</div>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="quick-item" @click="handleChangePassword">
                  <div class="icon">🔐</div>
                  <div class="text">修改密码</div>
                </div>
              </a-col>
            </a-row>
          </a-card>

          <!-- 数据统计 -->
          <a-card title="数据统计" class="stat-card" :bordered="false" style="margin-top: 24px">
            <a-row :gutter="16">
              <a-col :span="8">
                <div class="stat-item">
                  <div class="number">42</div>
                  <div class="label">上传图片</div>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="stat-item">
                  <div class="number">128</div>
                  <div class="label">收藏图片</div>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="stat-item">
                  <div class="number">365</div>
                  <div class="label">登录天数</div>
                </div>
              </a-col>
            </a-row>
          </a-card>

          <!-- 装饰区域 -->
          <div class="decoration-box">
            <div class="decoration-emoji">🎨</div>
            <div class="decoration-text">保持热爱，奔赴山海</div>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 编辑信息弹窗 -->
    <a-modal
      v-model:open="editVisible"
      title="编辑资料"
      width="480px"
      @ok="handleSaveEdit"
      :confirm-loading="editLoading"
    >
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="用户名" name="userName">
          <a-input v-model:value="editForm.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="个人简介" name="userProfile">
          <a-textarea
            v-model:value="editForm.userProfile"
            :rows="4"
            placeholder="用一句话介绍自己吧~"
            show-count:maxlength="100"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改密码弹窗 -->
    <a-modal
      v-model:open="passwordVisible"
      title="修改密码"
      width="400px"
      @ok="handleChangePasswordSubmit"
      :confirm-loading="passwordLoading"
    >
      <a-form :model="passwordForm" layout="vertical">
        <a-form-item label="原密码" name="oldPassword">
          <a-input-password v-model:value="passwordForm.oldPassword" placeholder="请输入原密码" />
        </a-form-item>
        <a-form-item label="新密码" name="newPassword">
          <a-input-password v-model:value="passwordForm.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item label="确认新密码" name="confirmPassword">
          <a-input-password
            v-model:value="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { getLoginUserUsingGet, editUserUsingPost, changePasswordUsingPost, userLogoutUsingPost } from '@/api/userController'
import { uploadUsingPost } from '@/api/fileController'

const router = useRouter()

/* 用户信息 */
const userInfo = ref({
  id: '',
  userAccount: '',
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: '',
  createTime: '',
  updateTime: '',
})
const defaultAvatar =
  'https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/assets/img/ui.png'

/* 编辑资料 */
const editVisible = ref(false)
const editLoading = ref(false)
const editForm = reactive({
  userName: '',
  userProfile: '',
})

/* 修改密码 */
const passwordVisible = ref(false)
const passwordLoading = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

/* 获取用户信息 */
const fetchUserInfo = async () => {
  try {
    const res = await getLoginUserUsingGet()
    if (res.data.code === 0) {
      userInfo.value = res.data.data || {}
    } else {
      message.error(res.data.message || '获取用户信息失败')
    }
  } catch (error) {
    message.error('获取用户信息失败')
  }
}

/* 处理审核状态点击 */
const handleReviewStatusClick = () => {
  // 根据用户角色跳转到不同的审核页面
  if (userInfo.value.userRole === 'admin') {
    // 管理员跳转到图片管理页面
    router.push('/picture/manager')
  } else {
    // 普通用户跳转到待审核图片页面
    router.push('/review')
  }
}

/* 编辑资料 */
const handleEditInfo = () => {
  editForm.userName = userInfo.value.userName
  editForm.userProfile = userInfo.value.userProfile
  editVisible.value = true
}

const handleSaveEdit = async () => {
  editLoading.value = true
  try {
    const res = await editUserUsingPost({
      id: userInfo.value.id,
      userName: editForm.userName,
      userProfile: editForm.userProfile,
    })
    if (res.data.code === 0) {
      message.success('资料已更新')
      editVisible.value = false
      await fetchUserInfo()
    } else {
      message.error(res.data.message || '更新失败')
    }
  } catch (error) {
    message.error('更新失败')
  } finally {
    editLoading.value = false
  }
}

/* 修改密码 */
const handleChangePassword = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordVisible.value = true
}

const handleChangePasswordSubmit = async () => {
  if (!passwordForm.oldPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
    message.warning('请填写完整信息')
    return
  }

  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    message.warning('两次新密码不一致')
    return
  }

  passwordLoading.value = true
  try {
    const res = await changePasswordUsingPost({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmNewPassword: passwordForm.confirmPassword
    })

    if (res.data.code === 0) {
      message.success('密码修改成功')

      // 登出并跳转到登录页
      try {
        await userLogoutUsingPost()
      } catch (logoutError) {
        console.error('登出失败', logoutError)
      }

      // 跳转到登录页
      await router.push('/user/login')
    } else {
      message.error(res.data.message || '密码修改失败')
    }
  } catch (error) {
    message.error('密码修改失败')
  } finally {
    passwordLoading.value = false
  }
}

/* 头像更换 */
const handleAvatarChange = () => {
  // 创建一个隐藏的文件输入元素
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = 'image/*'
  fileInput.style.display = 'none'

  // 添加change事件监听器
  fileInput.onchange = async (event) => {
    const target = event.target as HTMLInputElement
    if (target.files && target.files[0]) {
      const file = target.files[0]

      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        message.error('只能上传图片文件！')
        return
      }

      // 验证文件大小（限制为2MB）
      if (file.size > 2 * 1024 * 1024) {
        message.error('图片大小不能超过2MB！')
        return
      }

      try {
        // 上传文件
        const res = await uploadUsingPost({}, file)
        if (res.data.code === 0) {
          // 更新用户头像URL
          const avatarUrl = res.data.data || ''

          // 使用editUserUsingPost更新用户头像
          const editRes = await editUserUsingPost({
            id: userInfo.value.id,
            userAvatar: avatarUrl,
            userName: userInfo.value.userName,
            userProfile: userInfo.value.userProfile
          })

          if (editRes.data.code === 0) {
            message.success('头像更新成功！')
            // 重新获取用户信息以更新头像显示
            await fetchUserInfo()
          } else {
            message.error(editRes.data.message || '头像更新失败')
          }
        } else {
          message.error(res.data.message || '上传失败')
        }
      } catch (error) {
        message.error('上传失败，请重试')
      }
    }
  }

  // 触发文件选择对话框
  document.body.appendChild(fileInput)
  fileInput.click()
  document.body.removeChild(fileInput)
}

/* 工具函数 */
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
/* 顶部封面 */
.user-center {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
}

.back-button {
  margin-bottom: 20px;
}

.cover-wrap {
  height: 220px;
  background: url('https://images.unsplash.com/photo-1506318137071-a8e063b4bec0?auto=format&fit=crop&w=1650&q=80')
    center/cover no-repeat;
  position: relative;
}

.cover-mask {
  position: absolute;
  inset: 0;
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(12px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #2c3e50;
}

.cover-emoji {
  font-size: 48px;
  margin-bottom: 8px;
}

.cover-title {
  font-size: 32px;
  font-weight: 600;
  letter-spacing: 2px;
}

.cover-sub {
  font-size: 14px;
  margin-top: 4px;
  opacity: 0.8;
}

/* 主体内容 */
.content-wrap {
  max-width: 1200px;
  margin: -40px auto 0;
  padding: 0 24px 40px;
  position: relative;
  z-index: 2;
}

/* 左侧档案卡片 */
.profile-card {
  border-radius: 20px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
  padding: 32px 24px;
  text-align: center;
}

.avatar-box {
  position: relative;
  display: inline-block;
}

.avatar-main {
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.avatar-badge {
  position: absolute;
  right: -4px;
  bottom: -4px;
  background: #fff;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  line-height: 32px;
  font-size: 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-edit-btn {
  margin-top: 12px;
  font-size: 13px;
}

.username {
  font-size: 24px;
  font-weight: 600;
  margin-top: 16px;
}

.account {
  color: #999;
  font-size: 14px;
  margin-bottom: 16px;
}

.profile-list {
  text-align: left;
}

.profile-list .item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.profile-list .item:last-child {
  border-bottom: none;
}

.profile-list .label {
  color: #666;
}

.profile-list .value {
  color: #333;
  max-width: 160px;
  text-align: right;
  white-space: pre-wrap;
}

.action-btns {
  margin-top: 24px;
}

/* 快捷入口 & 数据统计 */
.quick-card,
.stat-card {
  border-radius: 20px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
}

.quick-item {
  text-align: center;
  padding: 24px 0;
  border-radius: 12px;
  background: #fafbfc;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-item:hover {
  background: #eef7ff;
  transform: translateY(-4px);
}

.quick-item .icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.quick-item .text {
  font-size: 14px;
  color: #555;
}

.stat-item {
  text-align: center;
}

.stat-item .number {
  font-size: 32px;
  font-weight: 700;
  background: linear-gradient(135deg, #7bc8ff 0%, #ff7eb3 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.stat-item .label {
  margin-top: 4px;
  color: #666;
  font-size: 14px;
}

/* 装饰区域 */
.decoration-box {
  margin-top: 24px;
  text-align: center;
  padding: 32px 0;
  background: linear-gradient(135deg, #ffffff 0%, #f6f9ff 100%);
  border-radius: 20px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
}

.decoration-emoji {
  font-size: 48px;
  margin-bottom: 12px;
}

.decoration-text {
  font-size: 16px;
  color: #666;
  letter-spacing: 1px;
}

/* 响应式 */
@media (max-width: 768px) {
  .cover-title {
    font-size: 24px;
  }

  .content-wrap {
    padding: 0 16px 24px;
  }
}
</style>
